// 宜搭引入调用

//回调函数
var fn;

//是否初始化
var isInit = false;

var fnMap = {};

// 初始化通信
function initParentMsg(backFn = () => {}) {
  console.log('初始化了');
  fn = backFn;
  // 接收来自父页面的消息
  window.addEventListener('message', message);
}

// 取消监听
function closeMsg() {
  window.removeEventListener('message', message);
}

function message(event) {
  var maps = {
    userTokenInfo: userTokenInfo,
    sendRequestRs: sendRequestRs,
    resetToken: userTokenInfo,
  };

  console.log(event);

  if (typeof event.data != 'string') return;
  var data = JSON.parse(event.data);
  var func = maps[data.type];
  if (func) func(data);

  //初始化token
  if (data.type == 'userTokenInfo' && !isInit) {
    isInit = true;
    childInit();
    fn();
  }
}

// 获取用户token保存本地
function userTokenInfo(msg) {
  const { data } = msg;
  Object.keys(data).forEach(key => {
    window.localStorage.setItem(key, data[key]);
  });
  console.log('------------');
  console.log('宜搭已经处理好token了');
  console.log('------------');
}

// 处理请求方法
function sendRequestRs(msg) {
  const {
    data: { id, res },
  } = msg;
  if (fnMap[id]) {
    //成功
    if (res.success) {
      fnMap[id].success?.(res);
    } else {
      fnMap[id].error?.(res);
    }
    fnMap[id] = undefined;
  }
}

// 通信方法
function sendMsg(obj = {}) {
  var parentOrigin = window.localStorage.getItem('parentOrigin');
  // 示例: 向父页面发送初始消息

  if (window.parent.postMessage) {
    window.parent.postMessage(JSON.stringify(obj), parentOrigin);
  }
}

//退出登录方法 （通知 父 ）
function logout() {
  var obj = {
    type: 'logout',
    data: {},
  };
  sendMsg(obj);
}

//刷新token （通知 父）
function refreshToken(data = {}) {
  var obj = {
    type: 'refreshToken',
    data: {
      accessToken: window.localStorage.getItem('accessToken'),
      refreshToken: window.localStorage.getItem('refreshToken'),
      expireIn: window.localStorage.getItem('expireIn'),
      refreshExpireIn: window.localStorage.getItem('refreshExpireIn'),
      ...data,
    },
  };

  sendMsg(obj);
}

//嵌套页面ok （通知 父）
function childInit(data = {}) {
  var obj = {
    type: 'childInit',
    data: {
      ...data,
    },
  };
  sendMsg(obj);
}

//埋点 （通知 父）
function statistics(title, params) {
  var obj = {
    type: 'statistics',
    data: {
      title: title,
      params: params,
    },
  };
  sendMsg(obj);
}

//请求 （通知 父）
function sendRequest(url, params, funcObj) {
  var id = new Date().getTime() + '-' + getNum(5, 1, 100);
  fnMap[id] = funcObj;
  var obj = {
    type: 'sendRequest',
    data: {
      id: id,
      url: url,
      params: params,
    },
  };
  sendMsg(obj);
}

function getNum(count, min, max) {
  var randomNumbers = [];
  for (var i = 0; i < count; i++) {
    randomNumbers.push(Math.floor(Math.random() * (max - min + 1)) + min);
  }
  return randomNumbers;
}

window.yidaUtils = {
  initParentMsg,
  logout,
  refreshToken,
  closeMsg,
  sendMsg,
  statistics,
  sendRequest,
};
